<template>
  <NavbarPage title="">
    <h2>登录页面</h2>
    <van-form @submit="onSubmit">
      <van-field v-model="username" name="username" label="用户名" :rules="rules.username" />
      <van-field v-model="password" type="password" name="password" label="密码" :rules="rules.password" />
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit" style="background-color: #00a6aa">登录</van-button>
      </div>
    </van-form>
    <a href="#/reg" class="reg">注册用户</a>
  </NavbarPage>
</template>



<script>
  import NavbarPage from "@/layout/NavbarPage.vue";
  export default {
    name: "loginy",
    data() {
      return {
        username: "",
        password: "",
        // 把校验规则放这里是方便管理
        rules: {
          username: [{ required: true, message: "请填写用户名" }],
          password: [{ required: true, message: "请填写密码" }],
        },
      };
    },
    // 用就要注册组件
    components: {
      NavbarPage,
    },
    created() {
      // console.log("Login", this);
      this.username = this.$route.query.username
      this.$parent.showTabbar = false;

    },

    methods: {
      async onSubmit(values) {
        // console.log("submit", values);
        // 校验通过就发起ajax
        const backBata = await this.$request.post("users/login", values);
        console.log(backBata);

        if (backBata.data.code === 400) {
          this.$notify({ type: "danger", message: "用户名或密码错误" })

        } else if (backBata.data.code === 200) {
          localStorage.setItem('userInfo', JSON.stringify(backBata.data))
          const { targetUrl = '/mine' } = this.$route.query
          this.$router.replace(targetUrl)
        }

      },
    },
  };
</script>

<style>
  h2 {
    text-align: center;
  }

  .reg {
    padding-left: 20px;
  }
</style>